<?php 
namespace app\common\model;
class Valid{
    protected $valid_list = ['phone','uname','string','number','idcard','url'];
    /**
     * @name call方法
     */
    public function __call($method,$params){
        if(strtolower(substr($method,0,2)) == 'is'){
            //取得类型
            $type = self::parseName(substr($method,2))[0];
            $type = strtolower($type);
            if(in_array($type,$this->valid_list)){
                array_unshift($params,$type);
                return self::do_check($params);
            }
        }
        //接口不存在
        return getApiErrorCode('00404');
    }
    
    /**
     * @name 解析name
     * @param string $name
     * @return array 返回name和类型
     */
    private static function parseName($name)
    {
        return strpos($name, '/') ? explode('/', $name, 2) : [$name];
    }
    /**
     * @name 正则验证方法
     * @access public
     * @param array $data 验证的信息,规则如下
     *  ['验证的类型','验证的字符串','最小长度','最大长度']
     * @return boolean 是否通过验证
     */
    public function do_check($data){
        list($case, $str, $num1, $num2) = $data;
        $num1 = $num1 ?:0;
        $num2 = $num2 ?:'';
        switch ($case) {
            case 'string':
                //验证是否为指定长度的字母/数字组合
                $preg = "/^[a-zA-Z0-9-_=]{" . $num1 . "," . $num2 . "}$/";
                break;
            case 'uname':
                //验证是否为合法用户名
                $preg = "/^[\x{4e00}-\x{9fa5}a-zA-Z0-9]{" . $num1 . "," . $num2 . "}$/u";
                break;
            case 'number':
                //验证是否为指定长度数字
                $preg = "/^[0-9]{" . $num1 . "," . $num2 . "}$/i";
                break;
            case 'idcard':
                //验证身份证号码
                $preg = '/(^([\d]{15}|[\d]{18}|[\d]{17}x)$)/';
                break;
            case 'phone':
                //验证电话号码
                //$preg = "/^((\d{3})|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}$/";
                $preg = '/^(\+86)?1[34578]{1}\d{9}$/';
                break;
            case 'url':
                $preg = '/^http(s)?:\/\/.+/';
                break;
            default:
                return true;
        }
        return (preg_match($preg, $str)) ? true : false;
    }
}